<template>
  <div class="app-container">
    <el-card class="box-card" v-loading="isLoading">
      <div slot="header" class="clearfix">
        <span>{{$t('store.title')}}</span>
        <el-button style="float: right;" type="primary" :loading="isLoadSub" @click="submit" v-if="nodePower.includes('edit')">{{$t('common.save')}}</el-button>
      </div>
      <h4>{{ $t('goods.base') }}</h4>
      <ProForm ref="baseForm" :echo="baseEcho" :config="EFC" :rules="baseRules" :msg="$t('goods.noBase')"></ProForm>
      <h4>{{ $t('goods.else') }}</h4>
      <el-form label-position="top">
        <el-row :gutter="40">
          <el-col :span="device==='desktop' ? 12 : 24">
            <el-form-item>
              <el-checkbox-group v-model="checked">
                <el-checkbox v-for="(item, index) in options" :label="item" :key="index">{{$t('store.'+item)}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item :label="$t('store.minStock')" prop="minStock">
              <div class="df"><el-input-number class="f1" :min="0" v-model="elseForm.minStock" :disabled="!checked.includes('is_tips')"></el-input-number></div>
            </el-form-item>
            <el-form-item :label="$t('store.is_freight')" prop="freight_price">
              <div class="df"><el-input-number class="f1" :min="0" v-model="elseForm.freight_price" :disabled="!checked.includes('is_freight')"></el-input-number></div>
            </el-form-item>
            <el-form-item :label="$t('store.is_tostore')" prop="tostore_price">
              <div class="df"><el-input-number class="f1" :min="0" v-model="elseForm.tostore_price" :disabled="!checked.includes('is_tostore')"></el-input-number></div>
            </el-form-item>
            <el-form-item :label="$t('store.recharge')">
              <div class="df">
                <el-input type="number" :min="0" :placeholder="$t('store.recharge_min')" v-model="elseForm.recharge_min"></el-input><span class="mlr10">-</span>
                <el-input type="number" :min="0" :placeholder="$t('store.recharge_max')" v-model="elseForm.recharge_max"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="device==='desktop' ? 12 : 24">
            <el-form-item :label="$t('store.workday')">
              <div class="df aic mtb10" :class="{jcsb:device==='mobile'}" v-for="(item, index) in weeks" :key="item">
                <div class="lab-week">{{ $t('store.'+item) }}</div>
                <div class="time" :class="{f1:device==='mobile', mlr20:device==='desktop'}">
                  <input :class="{'inp-time': device==='mobile'}" type="time" v-model="elseForm.workday[index].start_time" :disabled="elseForm.workday[index].is_open==='0'"><span>-</span>
                  <input :class="{'inp-time': device==='mobile'}" type="time" v-model="elseForm.workday[index].end_time" :disabled="elseForm.workday[index].is_open==='0'">
                </div>
                <el-button type="primary" size="small" @click="toggleBusi(index)">{{ $t('store.'+(elseForm.workday[index].is_open==='1' ? 'open' : 'close')) }}</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { validEmail } from '@/utils/validate'
import { getStore, editStore } from '@/api'
import { store } from '@/form'
export default {
  name: 'MemberList',
  data() {
    return {
      isLoading: false,
      EFC: store,
      baseEcho: {},
      baseRules: {
        shop_name: [{required: true,message: this.$t('common.required'),trigger: "blur"}],
        shop_address: [{required: true,message: this.$t('common.required'),trigger: "blur"}],
        shop_phone: [{required: true,message: this.$t('common.required'),trigger: "blur"}],
        shop_mail: [
          {required: true,message: this.$t('common.required'),trigger: "blur"},
          {trigger: "blur",validator: (rule, value, callback) => validEmail(value) ? callback() : callback(new Error(this.$t('common.emailErr')))}
        ],
        shop_web: [{required: true,message: this.$t('common.required'),trigger: "blur"}],
      },
      checked: [],
      options: ['is_tips', 'is_freight', 'is_tostore'],
      elseForm: {
        shop_id: 1, 
        minStock: 0,
        freight_price: 0,
        tostore_price: 0,
        recharge_min: '',
        recharge_max: '',
        workday: []
      },
      weeks: ['mon', 'tue', 'wed', 'thur', 'fri', 'sat', 'sun'],
      isLoadSub: false
    }
  },
  created() {
    this.getStore()
  },
  methods: {
    // 獲取店鋪信息
    async getStore() {
      this.elseForm.workday = this.weeks.map((_,weekday)=>({weekday, start_time: '09:00', end_time: '18:00', is_open: '1'}))
      try {
        this.isLoading = true
        const {results: {
          shop_logo, shop_name, shop_address, shop_phone, shop_mail,shop_web,
          is_tips, is_freight, is_tostore,
          shop_id, minStock, freight_price, tostore_price, recharge_min, recharge_max,
          workday
        }} = await getStore()
        this.baseEcho = {shop_id, shop_logo, shop_name, shop_address, shop_phone, shop_mail,shop_web}
        const iss = {is_tips, is_freight, is_tostore}
        for (const i in iss) {
          if (iss[i]===1) {
            this.checked.push(i)
          }
        }
        Object.assign(this.elseForm, {shop_id, minStock, freight_price, tostore_price, recharge_min, recharge_max})
        this.elseForm.workday = workday.map(({weekday, start_time, end_time, is_open}) => ({weekday,start_time, end_time, is_open}))
      } catch (error) {
        
      } finally {
        this.isLoading = false
      }
    },
    // 是否營業
    toggleBusi(index){
      this.elseForm.workday[index].is_open = this.elseForm.workday[index].is_open==='1' ? '0' : '1'
    },
    // 提交
    async submit() {
      this.$refs.baseForm.submit(async data => {
        const {minStock, freight_price, tostore_price} = this.elseForm
        if (this.checked.includes('is_tips') && !minStock) return this.$message({message: this.$t('store.stockErr'), type: 'warning'})
        if (this.checked.includes('is_freight') && !freight_price) return this.$message({message: this.$t('store.freightErr'), type: 'warning'})
        if (this.checked.includes('is_tostore') && !tostore_price) return this.$message({message: this.$t('store.tostoreErr'), type: 'warning'})

        const iss = {}
        this.options.forEach(item => {
          iss[item] = this.checked.includes(item) ? 1 : 0
        });
        try {
          this.isLoadSub = true
          await editStore(Object.assign({}, data, iss, this.elseForm))
          this.$message({message: this.$t('common.success'),type: 'success'})
        } catch (error) {
          
        } finally {
          this.isLoadSub = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.lab-week {
  display: flex;
  align-items: center;
  justify-content: center;
  align-self: stretch;
  width: 40px;
  border-radius: 3px;
  background-color: #42B983;
  font-size: 12px;
  color: #fff;
}
.time {
  display: flex;
  justify-content: center;
  align-self: stretch;
}
.inp-time {
  width: 85px;
}
</style>
